package com.stone.im.geteway.netty;

import com.stone.im.geteway.websocket.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class WebSocketServer {

    private NioEventLoopGroup connectionThreadGroup;
    private NioEventLoopGroup ioThreadGroup;
    private ServerBootstrap server;
    ChannelFuture channelFuture;

    public static final int PORT = 8003;

    public WebSocketServer(){
        connectionThreadGroup = new NioEventLoopGroup();
        ioThreadGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(connectionThreadGroup, ioThreadGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        //因为基于http协议，使用http的编码和解码器
                        pipeline.addLast(new HttpServerCodec());
                        //是以块方式写，添加ChunkedWriteHandler处理器
                        pipeline.addLast(new ChunkedWriteHandler());
                        pipeline.addLast(new HttpObjectAggregator(8192));
                        pipeline.addLast(new WebSocketServerProtocolHandler("/"));
                        //自定义的handler ，处理业务逻辑
                        pipeline.addLast(new WebSocketHandler());
                    }
                });
    }

    @PostConstruct
    public void start(){
        this.channelFuture = server.bind(PORT);
        System.err.println("netty WebSocket服务启动成功");
    }
}
